package swf
{
	import com.hurlant.crypto.Crypto;
	import com.hurlant.crypto.symmetric.*;
	import com.hurlant.util.*;
	
	import flash.utils.*;
	public class AESCrypto
	{
		/** 加密方式 */
		public static var name:String = 'aes128-ecb';
		/** 填充方式 */
		public static var pad:String = 'pkcs5';
		public function AESCrypto()
		{
		}
		
		/**
		 * 对字节数组加密
		 * @param         keyStr                        密钥
		 * @param         encryptArr                要加密的字节数组
		 * @param        iv                                初始向量
		 * @return
		 */
		public static function encryptByteArray( keyStr:String, encryptArr:ByteArray, iv:String='' ):ByteArray
		{
			var kdata:ByteArray = AESCrypto.stringToByteArray(keyStr);
			var ivdata:ByteArray = AESCrypto.stringToByteArray(iv);
			
			var ipad:IPad = Crypto.getPad(pad);
			var cipher:ICipher = Crypto.getCipher(name, kdata, ipad); 
			ipad.setBlockSize(cipher.getBlockSize()); 
			if (cipher is IVMode) {
				var ivmode:IVMode = cipher as IVMode;
				ivmode.IV = ivdata;
			}
			cipher.encrypt(encryptArr);
			
			return encryptArr;
		}
		/**
		 * 对字节数组解密
		 * @param         keyStr                        密钥
		 * @param         decryptArr                要解密的字节数组
		 * @param        iv                                初始向量
		 * @return
		 */
		public static function decryptByteArray( keyStr:String, decryptArr:ByteArray, iv:String='' ):ByteArray
		{
			var kdata:ByteArray = AESCrypto.stringToByteArray(keyStr);
			var ivdata:ByteArray = AESCrypto.stringToByteArray(iv);
			
			var ipad:IPad = Crypto.getPad(pad);
			var cipher:ICipher = Crypto.getCipher(name, kdata, ipad); 
			ipad.setBlockSize(cipher.getBlockSize()); 
			if (cipher is IVMode) { 
				var ivmode:IVMode = cipher as IVMode;
				ivmode.IV = ivdata;
			}
			cipher.decrypt(decryptArr);
			
			return decryptArr;
		}
		/**
		 * String转ByteArray
		 */
		public static function stringToByteArray( str:String ):ByteArray
		{
			var byteArr:ByteArray = new ByteArray();
			byteArr.writeUTFBytes(str);
			
			return byteArr;
		}
	}
}